'use client';

import Box from '@/app/[locale]/admin/common/box';
import type { INginxLogReadRecord } from '@/interfaces';
import { type PrefixedTTranslatedFields } from '@/lib/dictionaries';
import { formatDate } from '@/lib/tool';
import UpdateNav from '@/app/[locale]/admin/log/nginx/nginx-config-scheduler/update-nav';
import { useRouter } from 'next/navigation';
import { useMutation, useQuery } from '@tanstack/react-query';
import {
  queryNginxLogIsSchedulerRunning,
  startNginxLogScheduler,
  stopNginxLogScheduler,
} from '@/services/api';
import classNames from 'classnames';
import useToast from '@/hooks/useToast';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function NginxLogSchedulerConfigAdminPage(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: INginxLogReadRecord[];
    translatedFields: PrefixedTTranslatedFields<'logAdminPage'>;
  },
) {
  const router = useRouter();
  const { show } = useToast();

  const queryNginxLogIsSchedulerRunningQuery = useQuery(
    ['/nginx', '/logs', '/is-scheduler-running', { type: 'ACCESS' }],
    async (context) => {
      return (await queryNginxLogIsSchedulerRunning({
        query: context.queryKey[3] as any,
      })) as boolean;
    },
    {
      enabled: !!source.find((item) => item.logType === 'ACCESS'),
    },
  );
  const queryNginxErrorLogIsSchedulerRunningQuery = useQuery(
    ['/nginx', '/logs', '/is-scheduler-running', { type: 'ERROR' }],
    async (context) => {
      return (await queryNginxLogIsSchedulerRunning({
        query: context.queryKey[3] as any,
      })) as boolean;
    },
    {
      enabled: !!source.find((item) => item.logType === 'ERROR'),
    },
  );

  const startNginxLogSchedulerMutation = useMutation(startNginxLogScheduler);
  const stopNginxLogSchedulerMutation = useMutation(stopNginxLogScheduler);

  function onClickUpdate(item: INginxLogReadRecord) {
    router.push(`nginx-config-scheduler/save?type=${item.logType}`);
  }

  async function onClickStartScheduler(item: INginxLogReadRecord) {
    try {
      await startNginxLogSchedulerMutation.mutateAsync({
        data: {
          type: item.logType,
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.startSchedulerCompleted,
      });

      setTimeout(() => {
        queryNginxLogIsSchedulerRunningQuery.refetch();
      }, 1000);
    } catch (e) {
      startNginxLogSchedulerMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  async function onClickStopScheduler(item: INginxLogReadRecord) {
    try {
      await stopNginxLogSchedulerMutation.mutateAsync({
        data: {
          type: item.logType,
        },
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.stopSchedulerCompleted,
      });

      setTimeout(() => {
        queryNginxErrorLogIsSchedulerRunningQuery.refetch();
      }, 1000);
    } catch (e) {
      stopNginxLogSchedulerMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <div className="row g-4">
      <div className="col-12">
        <Box>
          <UpdateNav translatedFields={translatedFields} />
        </Box>
      </div>
      <div className="col-12">
        <Box>
          <div className="card">
            <div className="card-body">
              <h6 className="card-subtitle mb-2 text-secondary">
                {translatedFields.total}
              </h6>
              <h5 className="card-title">{source.length}</h5>
            </div>
          </div>
        </Box>
      </div>
      <div className="col-12">
        <Box>
          <div className="card">
            <div className="card-body vstack gap-4">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="">
                        {translatedFields.logType}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.logFilePath}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.fixedDelaySeconds}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.autostart}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.errorMessage}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.generalizedProperties.updatedOn}
                      </th>
                      <th scope="col" className=""></th>
                    </tr>
                  </thead>
                  <tbody>
                    {source.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td className="">
                            {translatedFields.enums.logType[item.logType]}
                          </td>
                          <td className="">{item.logFilePath}</td>
                          <td className="">{item.fixedDelaySeconds}</td>
                          <td className="">{item.autostart + ''}</td>
                          <td className="">{item.errorMessage}</td>
                          <td className="">{formatDate(item.updatedOn)}</td>
                          <td className="">
                            <div className="hstack gap-2">
                              <button
                                onClick={onClickUpdate.bind(this, item)}
                                className="btn btn-sm btn-light"
                                type="button"
                              >
                                <i className="bi bi-pencil me-2"></i>
                                {translatedFields.update}
                              </button>

                              <button
                                disabled={
                                  startNginxLogSchedulerMutation.isLoading
                                }
                                onClick={onClickStartScheduler.bind(this, item)}
                                className={classNames(
                                  'btn btn-sm rounded-pill',
                                  queryNginxLogIsSchedulerRunningQuery.data
                                    ? 'btn-success'
                                    : 'btn-light',
                                )}
                                type="button"
                              >
                                {startNginxLogSchedulerMutation.isLoading ? (
                                  <Spinner classs="me-2" />
                                ) : (
                                  <i className="bi bi-clock me-2"></i>
                                )}

                                {queryNginxLogIsSchedulerRunningQuery.data
                                  ? translatedFields.schedulerRunning
                                  : translatedFields.startScheduler}
                              </button>

                              <button
                                disabled={
                                  stopNginxLogSchedulerMutation.isLoading
                                }
                                onClick={onClickStopScheduler.bind(this, item)}
                                type="button"
                                className="btn btn-sm btn-light"
                              >
                                {stopNginxLogSchedulerMutation.isLoading ? (
                                  <Spinner classs="me-2" />
                                ) : (
                                  <i className="bi bi-stopwatch me-2"></i>
                                )}

                                {queryNginxErrorLogIsSchedulerRunningQuery.data
                                  ? translatedFields.schedulerRunning
                                  : translatedFields.startScheduler}
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {source.length === 0 && <Nodata />}
            </div>
          </div>
        </Box>
      </div>
    </div>
  );
}
